package com.quanshu.exchange.support.net.core;

import com.quanshu.exchange.support.net.ApiCode;
import com.quanshu.exchange.support.net.ApiException;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.ToastHelper;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * 接收器基类
 */
public abstract class BaseObserver<T> implements Observer<T> {

    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onError(Throwable e) {
        onFailure(e);
    }

    @Override
    public void onNext(T t) {
        if (t instanceof BaseResponse) {
            BaseResponse baseResponse = (BaseResponse) t;
            if (baseResponse.getCode() == ApiCode.SUCCESS.getCode()) {
                onSuccess(t);
            } else {
                onFailure(new ApiException(baseResponse.getCode(), baseResponse.getMsg()));
            }
        } else {
            onFailure(new ApiException("数据解析失败"));
        }
    }

//    public void onFailure(RuntimeException e) {
//        LogUtil.printException(e);
//        ToastHelper.toast(e.getMessage());
//    }

    public void onFailure(Throwable e) {
        LogUtil.printException(e);
        ToastHelper.toast(e.getMessage());
    }

    public abstract void onSuccess(T response);
}
